import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// 渲染器的自定义API，这里放的是自定义的一些方法
const api = {}
const ipcApi = {
  request(api: string, data?: any) {
    return ipcRenderer.invoke('custom-ipc-request', { api, data })
  },
  send(channel: string, payload: any) {
    ipcRenderer.send(channel, payload)
  },
  on(channel: string, callback: (payload: any) => void) {
    const listener = (_event: IpcRendererEvent, payload: any) => callback(payload)
    ipcRenderer.on(channel, listener)
    return () => ipcRenderer.removeListener(channel, listener)
  },
  once(channel: string, callback: (payload: any) => void) {
    const listener = (_event: IpcRendererEvent, payload: any) => {
      ipcRenderer.removeListener(channel, listener)
      callback(payload)
    }
    ipcRenderer.on(channel, listener)
  },
  off(channel: string, callback: (payload: any) => void) {
    ipcRenderer.removeListener(channel, callback)
  }
}

// 使用`contextBridge` API将Electron API暴露给
// 仅当启用了上下文隔离时才渲染器，否则
// 只需添加到DOM全局。
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
    contextBridge.exposeInMainWorld('ipc', ipcApi)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts) 这个是用来不让eslint报错的
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
  // @ts-ignore (define in dts)
  window.ipc = ipcApi
}
